import machine,time,math

#注意这个模块暂时不要接5v的电
#根据官方文档描述这个的最大测量应该在3V左右
#其中sw按键单独接吧 这里只读行程

class Rocker:
    TotalLeveValue=4096
    def __init__(self,pinX,pinY):
        self.x=machine.ADC(machine.Pin(pinX),atten=machine.ADC.ATTN_11DB);
        self.y=machine.ADC(machine.Pin(pinY),atten=machine.ADC.ATTN_11DB);
        self._leveValue=372#波峰值
        self._leveCount=11#阶梯值
        self._centerLeveIndex=5
        pass
    
    def initLeveValue(self):
        getV = self.getData(model=3)
        _min = getV[0]
        _max = getV[0]
        _count = 1000
        while _count:#获取1s以内遥感波动范围
            getV = self.getData(model=3)
            if getV[0] < _min:
                _min=getV[0]
            if getV[0] > _max:
                _max=getV[0]
                
            time.sleep_ms(1);
            _count=_count-1
            pass
        leve=_max-_min+5#增加少许区间避免测量不精准
        leveCount = math.ceil(Rocker.TotalLeveValue/leve)
        if leveCount%2 == 0:
           pass
        else:
            while leveCount%2 == 1:
                leve=leve+1#加大区间范围
                leveCount = math.ceil(Rocker.TotalLeveValue/leve)
            pass
        
        self._leveValue=int(leve)
        self._leveCount=leveCount
        print(leve,leveCount,self.leveValue(getV[0]))
        pass
    
    def getData(self,model=0):
        if model == 0:#所有数据（xy轴为修正数据）
            return (self.leveValue(self.x.read()),self.leveValue(self.y.read()),self.x.read_uv(),self.y.read_uv());
        elif model == 1:#xy轴偏移后修正数据
            return (self.leveValue(self.x.read()),self.leveValue(self.y.read()));
        elif model == 2:#xy轴偏移电压数据
            return (self.x.read_uv(),self.y.read_uv());
        elif model == 3:#xy轴偏移原始数据
            return (self.x.read(),self.y.read());
        elif model == 4:#修正后数据百分比数据
            return (self.leveValue(self.x.read())/self._leveCount,self.leveValue(self.y.read())/self._leveCount);   
        pass
    
    def leveValue(self,value):
        return math.floor(value/self._leveValue)
    
    pass



if __name__ == '__main__':
    roc=Rocker(34,35)
    roc.initLeveValue()
    while True:
        print(roc.getData(3))
        #print(roc.getData(4))
        time.sleep_ms(100)
        pass
